const app = getApp();
import getUserCard from "../../utils/getUserCard.js";
const utils = require('../../utils/util.js');
const sharePost = require('../../utils/sharePost.js');
Component({
  /**
   * 生成商品海报并保存图片组件
   * 组件的属性列表
   */
  properties: {
    pimages: { // 属性名
      type: String,
      value: ''
    },
    pid: { // 属性名
      type: String,
      value: ''
    },
    price: { // 属性名
      type: String,
      value: ''
    },
    productname: { // 属性名
      type: String,
      value: ''
    },
    shadowprice: {//优惠政策
      type: String,
      value: ''
    },
    salecount: {//销量
      type: String,
      value: ''
    },
    seltoid: {
      type: String,
      value: ''
    },
    saleuid: {
      type: String,
      value: ''
    },
    prostaffid: {
      type: String,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    productCode: "",
    showpost: false,
    imgHeight: 0,
    nameHeight: 0,
    priceHeight: 0,
    top: 30,
    shareimgpath: '',
    slider: '',
    company: '',
    proNameWidth: 0,
    priceWidth: 0,
    shadowpriceWidth: 0,
    saleCountWidth: 0,
    windowWidth: 330
  },

  ready: function () {
    // if (this.data.pid) {
    //   this.getWxaCode(this.data.pid)
    // }
    if (this.data.seltoid > 0) {
      this.getInfo(this.data.seltoid)
    }
    var windowWidth = wx.getSystemInfoSync().windowWidth * 0.88;
    this.setData({
      windowWidth: windowWidth
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取商品二维码
    getWxaCode: function (pid,callback) {
      var that = this
      var cardId = wx.getStorageSync("cardId");
      wx.request({
        url: app.globalData.host + "/api/Store/GetWxaCodeFile",
        data: {
          storeId: app.globalData.storeId,
          path: 'pages/index/index?t=2&p=' + cardId + '#' + pid + '#' + that.data.saleuid + '#' + that.data.prostaffid,
          storeappid: app.globalData.storeAppId
        },
        success: function (res) {
          if (res.data.Code == 0) {
            if (res.data.Data) {
              that.data.productCode = 'https://static.711688.net.cn/upload/user/' + res.data.Data;
              if(callback){
                callback();
              }              
            }
          }
        },
      })
    },
    //获取商家信息
    getInfo: function (createUid) {
      var that = this;
      getUserCard(createUid, function (cardid) {
        wx.request({
          url: app.globalData.host + "/api/Staff/GetInfo?id=" + cardid,
          success: function (res) {
            if (res.data.Code == 0) {
              let slider = '';
              if (res.data.Data.IndustryCode > 0) {//商家
                let sliders = res.data.Data.Slides;
                sliders = sliders.split(",");
                slider = sliders[sliders.length - 1];
              } else {//个人版
                slider = res.data.Data.Avater;
              }
              that.data.slider = slider;
              that.setData({
                company: res.data.Data.Company
              })
            }
          },
        })
      })
    },
    getProduct: function (pid) {
      let that = this;
      wx.request({
        url: app.globalData.host + '/api/Store/Product?pid=' + pid + '&isExtend=1',
        success: function (res) {
          if (res.data.Code == 0) {
            var p = res.data.Data;
            if (p.Extend) {
              if (p.Extend.AddUid > 0) {
                that.getInfo(p.Extend.AddUid);
              }
            }
          }
        }
      })
    },  
    getAvaterInfo: function (pid = 0) {
      let that = this;
      pid = pid==0 ? this.data.pid : pid;
      that.getWxaCode(pid,()=>{
        that.getProduct();
      });
    },
    //下载产品图片
    getProduct: function () {
      var that = this;
      that.setData({showpost: true,})
      var productImage = that.data.pimages;
      if (productImage) {
        wx.downloadFile({
          url: productImage,
          success: function (res) {
            if (res.statusCode === 200) {
              var productSrc = res.tempFilePath;
              that.calculateImg(productSrc, function (data) {
                that.getQrCode(productSrc, data);
              })
            } else {
              wx.showToast({
                title: '产品图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var productSrc = "";
                  that.getQrCode(productSrc);
                }
              })
            }
          }
        })
      } else {
        var productSrc = "";
        that.getQrCode(productSrc);
      }
    },

    //下载产品二维码
    getQrCode: function (productSrc, imgInfo = "") {
      var that = this;
      var productCode = that.data.productCode;
      wx.showLoading({title: '生成中...',mask: true,});
      if (productCode) {
        wx.downloadFile({
          url: productCode,
          success: function (res) {
            wx.hideLoading();
            if (res.statusCode === 200) {
              var codeSrc = res.tempFilePath;
              that.getSlider(productSrc, codeSrc, imgInfo);
            } else {
              wx.showToast({
                title: '二维码下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var codeSrc = "";
                  that.getSlider(productSrc, codeSrc, imgInfo);
                }
              })
            }
          }
        })
      } else {
        wx.hideLoading();
        var codeSrc = "";
        that.getSlider(productSrc, codeSrc);
      }
    },

    //下载商家头图
    getSlider: function (productSrc, codeSrc, imgInfo = "") {
      var that = this;
      var slider = that.data.slider;
      if (slider) {
        slider = utils.formatAvater(slider, 'https://static.711688.net.cn/upload/card/source/');
        wx.downloadFile({
          url: slider,
          success: function (res) {
            if (res.statusCode === 200) {
              var slider = res.tempFilePath;
              that.getAvater(productSrc, codeSrc, slider, imgInfo);
            } else {
              wx.showToast({
                title: '图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var slider = "";
                  that.getAvater(productSrc, codeSrc, slider, imgInfo);
                }
              })
            }
          }
        })
      } else {
        var slider = "";
        that.getAvater(productSrc, codeSrc, slider);
      }
    },

    // 获取用户头像
    getAvater: function (productSrc, codeSrc, slider, imgInfo) {
      var that = this;
      if (app.globalData.userInfo.Avatar) {
        wx.downloadFile({
          url: app.globalData.userInfo.Avatar,
          success: function (res) {
            if (res.statusCode === 200) {
              var avater = res.tempFilePath;
              that.sharePosteCanvas(productSrc, codeSrc, slider, avater, imgInfo);
            } else {
              wx.showToast({
                title: '图片下载失败！',
                icon: 'none',
                duration: 2000,
                success: function () {
                  var avater = "";
                  that.sharePosteCanvas(productSrc, codeSrc, slider, avater, imgInfo);
                }
              })
            }
          },
          fail: function (err) {
            var avater = "";
            that.sharePosteCanvas(productSrc, codeSrc, slider, avater, imgInfo);
          }
        })
      } else {
        var avater = "";
        that.sharePosteCanvas(productSrc, codeSrc, slider, avater);
      }
    },

    //canvas绘制分享海报
    sharePosteCanvas: function (productSrc, codeSrc, slider, avater, imgInfo) {
      wx.showLoading({
        title: '生成中...',
        mask: true,
      })
      var that = this;
      const ctx = wx.createCanvasContext('myCanvas', that);
      const query = wx.createSelectorQuery().in(this);
      query.select('#canvas-container').boundingClientRect(function (rect) {
        var height = rect.height;
        var width = rect.width;

        const grd = ctx.createLinearGradient(0, 0, 0, height / 2);
        grd.addColorStop(0, '#FCCA01');
        grd.addColorStop(1, '#FD8417');
        ctx.setFillStyle(grd);
        // ctx.fillRect(0, 0, width, height,);

        ctx.save();
        var bw = width;
        var bh = height;
        var bx = 0;
        var by = 0;
        var br = 10;
        ctx.beginPath()
        ctx.moveTo(bx + br, by)
        ctx.arcTo(bx + bw, by, bx + bw, by + bh, br)
        ctx.arcTo(bx + bw, by + bh, bx, by + bh, br)
        ctx.arcTo(bx, by + bh, bx, by, br)
        ctx.arcTo(bx, by, bx + bw, by, br)
        ctx.closePath();
        ctx.clip()
        ctx.fillRect(0, 0, width, height);
        ctx.restore() // 返回上一状态

        if (slider) {
          sharePost.circleImg(ctx, slider, width * 0.03, 11, 12);
        }

        ctx.font = '16px sans-serif';
        ctx.fillStyle = '#000';
        ctx.setTextAlign('left');

        let company = that.data.company;
        let companyLength = width - 46 - width * 0.06;
        let companyByte = Math.floor(companyLength / 15);
        if (company.length > companyByte) {
          company = company.substr(0, companyByte) + '...';
        }
        ctx.fillText(company, width * 0.03 + 35, 28);//姓名

        var imgheght = width * 0.94;
        if (imgInfo) {
          imgheght = parseFloat(imgInfo);
        }

        sharePost.fillRoundRect(ctx, width * 0.03, 45, width * 0.94, imgheght + that.data.nameHeight + that.data.priceHeight + 23, 4, 'rgba(255, 255, 255, 1)');

        // 产品头图
        if (productSrc) {
          ctx.drawImage(productSrc, 0, 0, width * 0.94, imgheght);
        }

        let productname = that.data.productname;
        let nameLength = width - 30 - width * 0.04;
        let nameByte = Math.floor(nameLength / 17);
        ctx.font = 'bold 18px sans-serif';
        ctx.fillStyle = '#000';

        const CONTENT_ROW_LENGTH = 2 * nameByte; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = sharePost.textByteLength(productname, CONTENT_ROW_LENGTH);
        let contentHh = 22 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          if (m < 2) {
            if (contentArray.length > 2 && m == 1) {
              contentArray[m] = contentArray[m].substr(0, contentArray[m].length - 2) + '...';
            }
            ctx.fillText(contentArray[m], width * 0.02, imgheght + 25 + contentHh * m);
          } else {
            break;
          }

        }

        //  产品金额
        let price = '¥' + that.data.price;
        ctx.font = 'bold 25px sans-serif';
        ctx.fillStyle = '#FE0909';
        ctx.setTextAlign('left');
        ctx.fillText(price, width * 0.01, imgheght + that.data.nameHeight + 35); //价格

        //优惠政策
        if (that.data.shadowprice) {
          ctx.font = '12px sans-serif';
          ctx.fillStyle = '#A6A6A6';
          var shadowprice = that.data.shadowprice;
          ctx.fillText(shadowprice, width * 0.02 + that.data.priceWidth, imgheght + that.data.nameHeight + 34); //优惠政策
        }

        // 销量
        let salecount = that.data.salecount
        if (salecount > 19) {
          ctx.setTextAlign('left');
          ctx.font = '12px sans-serif';
          ctx.fillStyle = '#A6A6A6';
          var saleCount = '销量：' + salecount;
          if (that.data.priceHeight > 20) {
            ctx.fillText(saleCount, width * 0.02, imgheght + that.data.nameHeight + 52); //销量
          } else {
            ctx.fillText(saleCount, width * 0.02 + that.data.priceWidth + that.data.shadowpriceWidth + 10, imgheght + that.data.nameHeight + 34); //销量
          }
        }

        if (avater) {
          sharePost.circleImg(ctx, avater, 0, imgheght + that.data.nameHeight + that.data.priceHeight + 40, 12);
        }
        if (app.globalData.userInfo) {
          let NickName = app.globalData.userInfo.NickName;
          if (NickName.length > 12) {
            NickName = NickName.substr(0, 12) + '...';
          } else {
            NickName = NickName;
          }
          ctx.font = '16px sans-serif';
          ctx.fillStyle = '#FFFFFF';
          ctx.setTextAlign('left');
          ctx.fillText(NickName, 30, imgheght + that.data.nameHeight + that.data.priceHeight + 60);
          ctx.font = '14px sans-serif';
          ctx.fillStyle = '#FFFFFF';
          ctx.setTextAlign('left');
          ctx.fillText('长按识别二维码  去看看 ->', 0, imgheght + that.data.nameHeight + that.data.priceHeight + 88);
        }

        //  产品二维码
        if (codeSrc) {
          sharePost.circleImg(ctx, codeSrc, width - 84, imgheght + that.data.nameHeight + that.data.priceHeight + 38, 32, 32);
        }

      }).exec()
      setTimeout(function () {
        ctx.draw();
        wx.hideLoading();
      }, 1000)
    },

    //点击保存到相册
    saveShareImg: function () {
      var that = this;
      wx.showLoading({
        title: '正在保存',
        mask: true,
      })
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success: function (res) {
            wx.hideLoading();
            var tempFilePath = res.tempFilePath;
            wx.saveImageToPhotosAlbum({
              filePath: tempFilePath,
              success(res) {
                wx.showModal({
                  content: '图片已保存到相册，赶紧晒一下吧~',
                  showCancel: false,
                  confirmText: '好的',
                  confirmColor: '#333',
                  success: function (res) {
                    that.closePoste();
                    if (res.confirm) { }
                  }
                })
              },
              fail: function (res) {
                wx.showToast({
                  title: '请删掉小程序再重新授权允许保存至相册',
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          },
        }, that);
      }, 1000);
    },


    closePoste: function () {
      this.setData({
        showpost: false
      })
      var myEventDetail = {
        showVideo: true
      } // detail对象，提供给事件监听函数
      this.triggerEvent('myevent', myEventDetail)
    },

    //计算图片尺寸
    calculateImg: function (src, cb) {
      var that = this;
      let productname = that.data.productname;
      let price = '¥' + that.data.price;
      let shadowprice = that.data.shadowprice;
      let salecount = that.data.salecount;

      let windowWidth = that.data.windowWidth;
      let nameLength = windowWidth - 30 - windowWidth * 0.04;
      let nameByte = Math.floor(nameLength / 17);
      let CONTENT_ROW_LENGTH = 2 * nameByte;
      let [contentLeng, contentArray, contentRows] = sharePost.textByteLength(productname, CONTENT_ROW_LENGTH);//产品标题行数、

      let priceWidth = price.length * 20;
      if (price.indexOf('.') != -1) {
        priceWidth = priceWidth - 20;
      }
      let shadowpriceWidth = shadowprice.length * 12;
      let saleCountWidth = salecount.toString().length * 12 + 30;
      if (salecount < 20) {
        saleCountWidth = 0;
      }
      let priceHeight = 20;
      if (priceWidth + shadowpriceWidth + saleCountWidth > windowWidth * 0.96 - 20) {
        priceHeight = 40
      }
      let namerows = contentArray.length;
      if (namerows > 2) {
        namerows = 2;
      }
      that.data.priceWidth = priceWidth;
      that.data.shadowpriceWidth = shadowpriceWidth;
      that.data.saleCountWidth = saleCountWidth;
      that.setData({
        nameHeight: 22 * namerows,
        priceHeight: priceHeight
      })

      wx.getImageInfo({
        src: src,
        success(res) {
          wx.getSystemInfo({
            success(res2) {
              var ratio = res.width / res.height;
              var imgHeight = (res2.windowWidth * 0.85 / ratio) + 130;
              that.setData({ imgHeight: imgHeight })
              cb(imgHeight - 130);
            }
          })
        }
      })
    }
  }
})